﻿#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <vector>
#include <typeinfo>
#include <exception>
#include<list>
using namespace std;
void test1()
{
	// 对应隐式类型转换--数据的解释意义没有改变

	double d = 12.34;
	int a = static_cast<int>(d);
	cout << a << endl;
	int&& ref = static_cast<int&&>(a);
	// 对应强制类型转换--数据的解释意义已经发⽣改变
	int* p1 = reinterpret_cast<int*>(a);
	// 对应强制类型转换中有⻛险的去掉const属性
	// 所以要注意加volatile
	volatile const int b = 0;
	int* p2 = const_cast<int*>(&b);
	*p2 = 1;
	cout << b << endl;
	cout << *p2 << endl;
	// 对应类型名查询
	cout << typeid(d).name() << endl;
	cout<<typeid(a).name()<<endl;
	cout << typeid(ref).name() << endl;
	cout << typeid(p1).name() << endl;
	cout << typeid(p2).name() << endl;
	cout<<typeid(b).name()<<endl;
}
class A
{
public:
	virtual void f() {}
	int _a = 1;
};
class B : public A
{
public:
	int _b = 2;
};
void fun1(A* pa)
{
	// 指向⽗类转换时有⻛险的，后续访问存在越界访问的⻛险

		// 指向⼦类转换时安全

	B* pb1 = (B*)pa;
	cout << "pb1:" << pb1 << endl;
	cout << pb1->_a << endl;
	cout << pb1->_b << endl;
	pb1->_a++;
	pb1->_b++;
	cout << pb1->_a << endl;
	cout << pb1->_b << endl;
}
void fun2(A* pa)
{
	// dynamic_cast会先检查是否能转换成功(指向⼦类对象)，能成功则转换，
	// (指向⽗类对象)转换失败则返回nullptr
	B* pb1 = dynamic_cast<B*>(pa);
	if (pb1)
	{
		cout << "pb1:" << pb1 << endl;
		cout << pb1->_a << endl;
		cout << pb1->_b << endl;
		pb1->_a++;
		pb1->_b++;
		cout << pb1->_a << endl;
		cout << pb1->_b << endl;
	}
	else
	{
		cout << "转换失败" << endl;
	}
}
void fun3(A& pa)
{
	// 转换失败，则抛出bad_cast异常
	try 
	{
		B& pb1 = dynamic_cast<B&>(pa);
		cout << "转换成功" << endl;
	}
	catch (const exception& e)
	{
		cout << e.what() << endl;
	}
}
void test2()
{
	A a;
	B b;
	//fun1(&a);
	//fun1(&b);
	fun2(&a);
	fun2(&b);
	fun3(a);
	fun3(b);
}
int main()
{
	test1();
	return 0;
}